//
//  QSAnimationManager.swift
//  TestSwift
//
//  Created by Song on 2018/6/26.
//  Copyright © 2018年 Song. All rights reserved.
//

import UIKit

class QSAnimationManager: NSObject {
    /// 旋转
    ///
    /// - Parameters:
    ///   - view: 哪个view旋转
    ///   - duration: 旋转一周的时间
    class func qs_rotationAnimation(_ view: UIView, duration: CFTimeInterval = 1.2) {
        // 创建动画
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
        
        // 设置动画的属性
        rotationAnim.fromValue = 0
        rotationAnim.toValue = Double.pi * 2
        rotationAnim.repeatCount = MAXFLOAT
        rotationAnim.duration = duration
        // 这个属性很重要 如果不设置当页面运行到后台再次进入该页面的时候 动画会停止
        rotationAnim.isRemovedOnCompletion = false
        
        // 将动画添加到layer中
        view.layer.add(rotationAnim, forKey: nil)
    }
    
    /// 转场动画
    ///
    /// - Parameters:
    ///   - view: 哪个view做转场
    ///   - toFrame: 移动到哪个位置
    ///   - duration: 移动的时间
    ///   - completion: 动画完成的闭包
    class func qs_transform(_ view: UIView, toFrame: CGRect, duration: CFTimeInterval = 0.35, completion: ((Bool) -> Void)?) {
        view.superview?.layoutIfNeeded()
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            UIView.animate(withDuration: duration, animations: {
                view.frame = toFrame
                view.alpha = 1.0
            }, completion: completion)
        }
    }
    
    /// 透明度渐变
    ///
    /// - Parameters:
    ///   - view: 哪个view做渐变
    ///   - alpha: 透明度
    ///   - duration: 时间周期
    ///   - completion: 动画完成的闭包
    class func qs_alphaGradual(_ view: UIView, alpha: CGFloat = 1.0, duration: CFTimeInterval = 0.35, completion: ((Bool) -> Void)?) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            UIView.animate(withDuration: duration, animations: {
                view.alpha = alpha
            }, completion: completion)
        }
    }
    
    
    /// 摇晃动画
    ///
    /// - Parameters:
    ///   - view: 执行动画的view
    ///   - duration: 时间周期
    class func qs_shakeAnimate(_ view: UIView, duration: CFTimeInterval = 0.35) {
        let anim = CAKeyframeAnimation.init()
        anim.keyPath = "transform.rotation"
        anim.duration = duration
        anim.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
        anim.values = [(-10 / 180.0 * CGFloat.pi), (10 / 180.0 * CGFloat.pi), (-10 / 180.0 * CGFloat.pi)]
        anim.isRemovedOnCompletion = false
        anim.fillMode = kCAFillModeForwards
        
        view.layer.add(anim, forKey: "shake")
    }
}
